package com.xzixi.websocket.interceptablewebsocketdemo.websocket;

import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author 薛凌康
 */
public class SessionIdRegistry {

    private final Map<String, Set<String>> userSessionIds = new ConcurrentHashMap<>();

    /**
     * 根据用户id获取sessionId集合
     * @param username 用户名
     * @return sessionId集合
     */
    public Set<String> getSessionIds(String username) {
        Set<String> sessionIds = this.userSessionIds.get(username);
        return sessionIds!=null? sessionIds: Collections.emptySet();
    }

    public Map<String, Set<String>> getAllSessionIds() {
        return this.userSessionIds;
    }

    /**
     * 登记sessionId
     * @param username 用户名
     * @param sessionId websocket sessionId
     */
    public void registerSessionId(String username, String sessionId) {
        Set<String> sessionIds = userSessionIds.get(username);
        if (sessionIds==null) {
            sessionIds = new CopyOnWriteArraySet<>();
            this.userSessionIds.put(username, sessionIds);
        }
        sessionIds.add(sessionId);
    }

    /**
     * 移除sessionId
     * @param username 用户名
     * @param sessionId websocket sessionId
     */
    public void unRegisterSessionId(String username, String sessionId) {
        Set<String> sessionIds = userSessionIds.get(username);
        if (sessionIds!=null && sessionIds.remove(sessionId) && sessionIds.isEmpty()) {
            this.userSessionIds.remove(username);
        }
    }

}
